import 'package:base/main.dart';
import 'package:flutter/material.dart';
import 'package:framework/core/base_view_model.dart';
import 'package:get/get.dart';

/// 选择框和输入框VM管理
class SelectInputVM extends BaseViewModel {
  /// 下拉选择框 RX数据流
  final selectedFromValue = 0.obs;
  final selectedToValue = 0.obs;

  /// 存储控制器的 Map（通过 key 区分不同输入框）
  final _controllers = <String, TextEditingController>{};

  /// 下拉选择框-from
  updateFromValue(int tempValue) {
    selectedFromValue.value = tempValue;
  }

  /// 下拉选择框-to
  updateToValue(int tempValue) {
    selectedToValue.value = tempValue;
  }

  /// 初始化下拉框数据
  initSelectedData(String value) {
    List<String> items = (value ?? '')
        .split('-')
        .map((e) => e.trim())
        .where((e) => e.isNotEmpty)
        .toList();
    if (items.length < 2) {
      items = ['0', '0'];
    }
    final from = items[0].isEmpty ? '0' : items[0];
    final to = items.length > 1 ? items[1] : '0';
    selectedFromValue.value = int.parse(from);
    selectedToValue.value = int.parse(to);
  }

  /// 动态获取输入框控制器（懒初始化）
  TextEditingController getController(String key) {
    return _controllers.putIfAbsent(key, () {
      final controller = TextEditingController();
      return controller;
    });
  }

  /// 重置所有输入框控制器
  resetAll() {
    selectedFromValue.value = 0;
    selectedToValue.value = 0;
    _controllers.clear();
  }

  /// 条件重置输入框控制器
  resetByKey(String key) {
    _controllers["${key}_1"]?.clear();
    _controllers["${key}_2"]?.clear();
  }

  @override
  void onClose() {
    for (var c in _controllers.values) {
      c.dispose();
    }
    super.onClose();
  }
}
